package edu.ucsd.cse135.gas.logic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.ucsd.cse135.gas.logic.support.Database;

public class User {

	private String mail;
	private String password;
	private String role;
	
	public String getMail() {
		return mail;
	}
	
	public void setMail(String mail) {
		this.mail = mail;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public static boolean doesUserExist(String mail) {
	
		Connection conn = Database.open();
		
		/** First enter user name (mail) and password into users table **/
		
		try {
			String sql = "SELECT mail FROM users WHERE mail = ?;";
		
			PreparedStatement preStmt = conn.prepareStatement(sql);
			
			ResultSet rs = preStmt.executeQuery();

			boolean userExists = !rs.isLast();
			
			rs.close();
			preStmt.close();
			Database.close();
			
			return userExists;
		}
		catch(SQLException se)
		{
			Database.close();
			se.getCause();
			return true;
		}
	}
	
	/** Method to register a new user **/
	
	public boolean register() {
		
		Connection conn = Database.open();
			
		/** First enter user name (mail) and password into users table **/
		
		try {
			String sql = "INSERT INTO users VALUES (?, md5(?));";
		
			PreparedStatement preStmt = conn.prepareStatement(sql);
			preStmt.setString(1, mail);
			preStmt.setString(2, password);
			preStmt.executeUpdate();
			preStmt.close();
		}
		catch(SQLException se)
		{
			Database.close();
			se.getCause();
			return false;
		}
		catch(Exception e)
		{
			Database.close();
			e.getCause();
			return false;
		}
			
		/** Then map the role applicant on the new user **/
		
		try  {
			PreparedStatement preStmt = conn.prepareStatement("INSERT INTO user_role VALUES (?, 'applicant');");
			preStmt.setString(1, mail);			
			preStmt.executeUpdate();
			
			preStmt.close();
			Database.close();
			
			return true;
		}
		catch(Exception e)
		{
			Database.close();
			e.getCause();
			return false;
		}
	}
	
	//TODO populate user object with database information
	
	public void setUser(String mail) {
		
	}
}
